package com.better517na.elasticseach.handlers;



import com.better517na.elasticseach.elasticsearch.Index;
import com.better517na.elasticseach.elasticsearch.client.ESHttpClient;
import com.better517na.elasticseach.utils.FileUtils;
import com.better517na.elasticseach.utils.StringUtil;
import com.google.common.collect.Lists;

import java.util.List;


public class ImportDataHandler extends AbstractHandler implements Handler {

    public void doWork() {
        ESHttpClient consumer = new ESHttpClient(context.getEsHost(),context.getEsPort());
        Index index = context.getConsumer();
        List<String> files  = Lists.newArrayList();
        if(StringUtil.isNotEmpty(context.getFilePrefix()) && StringUtil.isNotEmpty(context.getInPut())){
             files = FileUtils.getFiles(context.getInPut(), context.getFilePrefix());
        }else{
             files = FileUtils.getFiles(FileUtils.getProperties("file.in"), FileUtils.getProperties("file.prefix"));
        }
        index.setAction("_bulk");
        for (String s : files){
            try {
                System.out.println("读取文件..." + s);
                String body = FileUtils.readFile(s);
                System.out.println("导入数据...");
                consumer.post(index,body);
                System.out.println("导入文件..."+ s +"成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
